package com.alibaba.otter.node.etl.load.loader.mq.rabbit.api;

import com.alibaba.otter.node.etl.load.loader.mq.rabbit.model.ConnectionSetting;
import com.alibaba.otter.node.etl.load.loader.mq.rabbit.model.RabbitMqNamespace;
import com.google.common.cache.CacheLoader;
import com.google.common.collect.Lists;
import com.rabbitmq.client.Address;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class RabbitMqConnectionLoader extends CacheLoader<RabbitMqNamespace, Connection> {

    @Override
    public Connection load(RabbitMqNamespace key) throws Exception {
        ConnectionSetting setting = key.getSetting();
        String addrs = setting.getAddrs();
        List<Address> addresses = Lists.newArrayList();
        if (addrs != null) {
            List<String> addressStrings = Arrays.asList(addrs.split(","));
            addresses = addressStrings.stream().map(addressStr -> {
                String[] hostAndPort = addressStr.split(":");
                return new Address(hostAndPort[0], Integer.parseInt(hostAndPort[1]));
            }).collect(Collectors.toList());
        } else {
            addresses.add(new Address(setting.getHost(), setting.getPort()));
        }
        ConnectionFactory factory = getConnectionFactory(setting);
        log.info("create connection for namespace: " + key.getName());
        return factory.newConnection(addresses);
    }

    private static ConnectionFactory getConnectionFactory(ConnectionSetting setting) {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername(setting.getUser());
        factory.setPassword(setting.getPwd());
        factory.setVirtualHost(setting.getVhost());
        factory.setAutomaticRecoveryEnabled(true);
        return factory;
    }


    public static void main(String[] args) {
        try {
            URI u = new URI("amqp://qamq-cc.intra.yeshj.com:5672");

            System.out.println(String.format("p:%s,url:%s,port:%s", u.getScheme(),u.getPath(), u.getPort()));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
}

